import requests
import json
import sys  
from PyQt5.QtWidgets import QApplication, QDialog, QMessageBox  
import Ui_chat
import os
import warn

API_KEY = "SO8K3o2U9qm2WVqH6w7qOHrO"
SECRET_KEY = "Jjo4bypthpWi6j36Gp8IRaHexl7d19t2"

data=''

class ChatBot(QDialog):
    def __init__(self, parent=None):  
        super(ChatBot, self).__init__(parent)  
        self.ui =Ui_chat.Ui_Form() 
        
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.send_message)
        self.ui.pushButton_2.clicked.connect(self.update_problem)
        self.ui.pushButton_3.clicked.connect(self.chat_analy)
        self.init_response()
        self.ui.pushButton.setText("回答")
        self.ui.pushButton_2.setText("新问题")
        self.ui.pushButton_3.setText("分析")
    def chat_analy(self):
        dl=len(data)
        if dl<100:
            self.warnWin = warn.warnwindow(self,dl)  
            self.warnWin.setWindowTitle("警告")
            self.warnWin.data_sent.connect(self.handle_data)
            self.warnWin.exec_()
        else:
            self.close()
    def update_problem(self,data):
        self.ui.textEdit_2.clear() 
        self.init_response()
    def handle_data(self,data):
        if data==1:
            self.warnWin.warn_setn()
            self.close()

    def send_message(self):
        message = self.ui.textEdit_2.toPlainText()
        messagelen = len(message)
        if messagelen>=10:
            print(message)
            self.ui.textEdit_2.clear() 
            self.ui.textEdit.append(f"YOU: {message}") 
            self.init_response()
            global data
            data+=str(message)
        else:
            msgbox = QMessageBox(self)  
            msgbox.setWindowTitle('信息')  
            if messagelen==0:
                msgbox.setText('请回答问题')
            else:
                msgbox.setText('请回答至少超过10个字') 
            msgbox.setIcon(QMessageBox.Information)  
            msgbox.setStandardButtons(QMessageBox.Ok)     
            ret = msgbox.exec_()  
 
    def get_response(self, message):
        url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + self.get_access_token()
        payload = json.dumps({
            "messages": [
                {
                    "role": "user",
                    "content": message
                }
            ]
        })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        return response.json()["result"]
 
    def get_access_token(self):
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))
    def init_response(self):
        s='提出一个复杂的情景交互问题，并等我回答\n有以下要求：\n1.一次只能问一个问题。\n2.只有在我回答后，你才能提出接下来的问题。\n3.除了问题不要有其它文本，比如“好的，我会按照您的要求来提出一个复杂的情景交互问题”。'
        response = self.get_response(s)
        self.ui.textEdit.append(f"BOT: {response}")

if __name__ == '__main__':
    app = QApplication(sys.argv)  
    mainWin = ChatBot()  
    mainWin.show()
    app.exec_()  
    sys.exit()


